package com.Filter;

import java.io.IOException;

import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * Servlet Filter implementation class servletFilter
 */
@WebFilter("/servletFilter")
public class servletFilter implements Filter {


	public servletFilter() {
		// TODO Auto-generated constructor stub
	}

	public void destroy() {
		// TODO Auto-generated method stub
	}


	public void doFilter(ServletRequest req, ServletResponse res, FilterChain chain) throws IOException, ServletException {
		req.setCharacterEncoding("UTF-8");        //设置字符编码
		res.setCharacterEncoding("UTF-8");
		HttpServletRequest request = (HttpServletRequest)req;
		HttpServletResponse reponse = (HttpServletResponse)res;
		//用户请求的地址
		String requestPath = request.getRequestURI();
		System.out.println("用户想请求:" + requestPath);
		if (requestPath.equals("/MyServlet/s")||requestPath.equals("/MyServlet/index.jsp")) {
			chain.doFilter(req, res);            //放行
			return ;                             //放行之后，就结束
		}
		//要登录才能放行的界面
		//要得到登录信息
		System.out.println("验证登录");
		if (request.getSession().getAttribute("userid") == null) {
			reponse.sendRedirect("login.jsp");
		} else {
			chain.doFilter(request, reponse);
			reponse.sendRedirect("login.jsp");
		}
		chain.doFilter(req, res);
	}

	public void init(FilterConfig fConfig) throws ServletException {
		// TODO Auto-generated method stub
	}

}
